﻿using ModuleViewD;
using Prism.Modularity;
using WpfMvvmTemplatePrismHC.Common;
using WpfMvvmTemplatePrismHC.Models.ProgramModel;
using WpfMvvmTemplatePrismHC.Tools.Helpers;
using WpfMvvmTemplatePrismHC.ViewModels.Dialogs;
using WpfMvvmTemplatePrismHC.ViewModels.UserControls;
using WpfMvvmTemplatePrismHC.Views.Dialogs;
using WpfMvvmTemplatePrismHC.Views.Main;
using WpfMvvmTemplatePrismHC.Views.UserControls;

namespace WpfMvvmTemplatePrismHC
{
    public partial class App : PrismApplication
    {
        public App()
        {
            #region 全局异常捕获

            //UI线程未捕获异常处理事件（UI主线程）
            this.DispatcherUnhandledException += (s, e) =>
            {
                if (e.Exception is Exception ex)
                {
                    LogHelper.WriteLog(ex.ToString());
                    e.Handled = true;//表示异常已处理，可以继续运行
                }
            };

            //非UI线程未捕获异常处理事件(例如自己创建的一个子线程)
            AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            {
                if (e.ExceptionObject is Exception ex)
                    LogHelper.WriteLog(ex.ToString());
            };

            //Task线程内未捕获异常处理事件
            TaskScheduler.UnobservedTaskException += (s, e) =>
            {
                if (e.Exception is Exception ex)
                {
                    LogHelper.WriteLog(ex.ToString());
                    e.SetObserved(); // 标记异常已被处理，避免程序崩溃
                }
            };

            #endregion 全局异常捕获

            #region 单实例运行

            //判断程序是否已经启动
            var ProcessName = Assembly.GetExecutingAssembly().GetName().Name;//程序集名称
            Process currentProcess = Process.GetCurrentProcess();//当运行的新进程

            // 通过程序集名称判断是否有进程已运行
            Process[] ps = Process.GetProcessesByName(ProcessName);

            // 因为新进程名也是ProcessName，所以ps的Length大于1时才是有多个进程
            if (ps.Length > 1)
            {
                foreach (var item in ps)
                {
                    // 找到非当前新进程的 MessageConstruction 进程对象
                    if (item.Id != currentProcess.Id)
                    {
                        //关闭之前的进程
                        item.Kill();
                    }
                }
            }

            #endregion 单实例运行

            #region 读取配置文件

            try
            {
                //读取配置文件

                string fileContent = File.ReadAllText(GlobalStaticData.AppSettingsFilePath);
                JObject? jObject = JObject.Parse(fileContent);

                GlobalStaticData.HardwareMode = (int)(jObject?["AppSettings"]?["HardwareMode"] ?? 0);

#if DEBUG
                LogHelper.WriteLog($"软件以 Debug 模式启动！");
#else
                LogHelper.WriteLog($"软件以 Release 模式启动！");
#endif
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.ToString());
            }

            #endregion 读取配置文件
        }

        #region 主题颜色

        internal void UpdateTheme(ApplicationTheme theme)
        {
            if (ThemeManager.Current.ApplicationTheme != theme)
            {
                ThemeManager.Current.ApplicationTheme = theme;
            }
        }

        internal void UpdateAccent(Brush accent)
        {
            if (ThemeManager.Current.AccentColor != accent)
            {
                ThemeManager.Current.AccentColor = accent;
            }
        }

        #endregion

        /// <summary>
        /// 创建主窗体
        /// </summary>
        /// <returns></returns>
        protected override Window CreateShell()
        {
            return Container.Resolve<MainWindowView>();
        }

        /// <summary>
        /// 注册容器
        /// </summary>
        /// <param name="containerRegistry">注册</param>
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            //直接在本项目中加载模块 注册导航容器
            //将视图类型 View 和视图模型类型 ViewViewModel 关联起来
            containerRegistry.RegisterForNavigation<ViewA, ViewAViewModel>();
            containerRegistry.RegisterForNavigation<ViewB, ViewBViewModel>();
            containerRegistry.RegisterForNavigation<ViewC, ViewCViewModel>();

            //注册对话框
            containerRegistry.RegisterDialog<InquiryDialogView, InquiryDialogViewModel>();

            //注册程序总类(单列)
            containerRegistry.RegisterSingleton<ProgramModel>();
        }

        /// <summary>
        /// 通过项目引用加载模块 
        /// </summary>
        /// <param name="moduleCatalog"></param>
        protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
        {
            moduleCatalog.AddModule<ModuleViewDModule>();
        }

        /// <summary>
        /// 通过dll路径加载模块 
        /// </summary>
        /// <returns></returns>
        protected override IModuleCatalog CreateModuleCatalog()
        {
            return new DirectoryModuleCatalog() { ModulePath= @".\ModuleDlls" };
        }

    }
}